package cn.com.thingo.hyintelligent.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.th.opensdk.openapi.NotificationInfo;
import com.th.opensdk.openapi.RoomInfo;
import com.th.opensdk.openapi.THOpenSDK;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.com.thingo.hyintelligent.R;
import cn.com.thingo.hyintelligent.app.App;
import cn.com.thingo.hyintelligent.base.BaseActivity;
import cn.com.thingo.hyintelligent.base.contract.SelectGatewayContract;
import cn.com.thingo.hyintelligent.model.bean.CommonBean;
import cn.com.thingo.hyintelligent.model.bean.GatewayListBean;
import cn.com.thingo.hyintelligent.presenter.SelectGatewayPresenter;
import cn.com.thingo.hyintelligent.ui.adapter.DeleteSwipeMenuCreator;
import cn.com.thingo.hyintelligent.ui.adapter.GatewayListViewAdapter;
import cn.com.thingo.hyintelligent.ui.receiver.THOpenReceiver;
import cn.com.thingo.hyintelligent.util.LogUtil;
import cn.com.thingo.hyintelligent.util.SPUtils;
import cn.com.thingo.hyintelligent.util.ToastUtil;
import cn.com.thingo.hyintelligent.widget.CommonDialogFragment;

/**
 * 选择网关页面
 */
public class SelectGatewayActivity extends BaseActivity<SelectGatewayPresenter> implements
        SelectGatewayContract.View, THOpenReceiver.CallBack, AdapterView.OnItemClickListener, SwipeMenuListView.OnMenuItemClickListener,
        CommonDialogFragment.CallBack {
    @BindView(R.id.toolbar_left)
    ImageView ivToolbarLeft;
    @BindView(R.id.toolbar_title)
    TextView tvTitle;
    @BindView(R.id.toolbar_right)
    ImageView ivToolbarRight;
    @BindView(R.id.select_gateway_list)
    SwipeMenuListView lvGatewayList;
    @BindView(R.id.login_hint)
    View loginProgress;

    private List<GatewayListBean.DataBean> gatewayList = new ArrayList<>();
    private GatewayListViewAdapter adapter;
    private THOpenReceiver receiver;
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    gatewayConnectFail();
                    App.getInstance().setGatewayLoginStatus(true);
                    break;
            }
        }
    };

    @Override
    protected int getLayout() {
        return R.layout.activity_select_gateway;
    }

    @Override
    protected void initEventAndData() {
        ivToolbarLeft.setImageResource(R.mipmap.back);
        ivToolbarRight.setImageResource(R.mipmap.add);
        ivToolbarRight.setVisibility(View.VISIBLE);
        tvTitle.setText(R.string.select_gateway);
        initView();
    }

    private void registerReceiver() {
        receiver = new THOpenReceiver(SelectGatewayActivity.this);
        IntentFilter filter = new IntentFilter();
        filter.addAction(NotificationInfo.BROADCAST_GATEWAY_STATUS_CHANGED);
        registerReceiver(receiver, filter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.gatewayList(SPUtils.newInstance().getString(SPUtils.LOGIN_TOKEN));
        registerReceiver();
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(receiver);
    }

    private void initView() {
        adapter = new GatewayListViewAdapter(gatewayList, mContext);
        lvGatewayList.setAdapter(adapter);
        lvGatewayList.setOnItemClickListener(this);
        lvGatewayList.setMenuCreator(new DeleteSwipeMenuCreator(mContext));
        lvGatewayList.setOnMenuItemClickListener(this);
        lvGatewayList.setSwipeDirection(SwipeMenuListView.DIRECTION_LEFT);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    //隐藏登录的进度条
    public void hideProgress() {
        loginProgress.setVisibility(View.GONE);
    }

    public void gatewayConnectFail() {
        ToastUtil.shortShow("登录失败，请检查网关！");
        hideProgress();
    }


    @Override
    public void viewGatewayList(GatewayListBean gatewayListBean) {
        List<GatewayListBean.DataBean> data = gatewayListBean.getData();
        gatewayList.clear();
        if (data != null && data.size() > 0) {
            gatewayList.addAll(data);
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void viewDeleteGatewayById(CommonBean commonBean) {
        mPresenter.gatewayList(SPUtils.newInstance().getString(SPUtils.LOGIN_TOKEN));
    }


    @OnClick({R.id.toolbar_left, R.id.toolbar_right})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.toolbar_left:
                int roomSize = THOpenSDK.getInstance().getRoomList().size();
                LogUtil.d(roomSize + "");
                finish();
                break;
            case R.id.toolbar_right:
                Intent intent = new Intent(SelectGatewayActivity.this, AddGatewayActivity.class);
                startActivity(intent);
                break;
        }
    }

    @Override
    public void callBack() {
        doSome();
    }

    public void doSome() {
        List<RoomInfo> roomList = THOpenSDK.getInstance().getRoomList();
        if (roomList.isEmpty()) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            doSome();
        } else {
            hideProgress();
            Intent mainIntent = new Intent(mContext, MainActivity.class);
            startActivity(mainIntent);
            finish();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (App.getInstance().isGatewayLoginStatus()) {
            App.getInstance().setGatewayLoginStatus(false);
            final GatewayListBean.DataBean dataBean = gatewayList.get(position);
            //授权
            loginProgress.setVisibility(View.VISIBLE);
            SPUtils.newInstance().put(SPUtils.GATEWAY_CURRENT, dataBean.getNumber());
            SPUtils.newInstance().put(SPUtils.GATEWAY_CURRENT_NAME, dataBean.getTitle());
            SPUtils.newInstance().put(SPUtils.GATEWAY_IS_CREATE, dataBean.getIs_creat());
            new Thread() {
                @Override
                public void run() {
                    App.setDataBean(dataBean);
                    int i = THOpenSDK.getInstance().loginGateway(dataBean.getNumber(), dataBean.getUsername(), dataBean.getPassword());
                    if (i != 0) {
                        handler.sendEmptyMessage(1);
                    }
                }
            }.start();
        } else {
            ToastUtil.shortShow("正在登录网关...");
        }
    }

    @Override
    public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
        switch (index) {
            case 0:
                //左滑菜单操作
                CommonDialogFragment fragment = new CommonDialogFragment(mContext, "刪除网关", "确认删除该网关？", "确认", position);
                fragment.show(getFragmentManager(), "delete_gateway");
                break;
        }
        return false;
    }

    @Override
    public void determine(int position) {
        mPresenter.deleteGatewayById(SPUtils.newInstance().getString(SPUtils.LOGIN_TOKEN), gatewayList.get(position).getId());
    }
}
